package org.groupg.project.step;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.EventHandlerGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class DisruptorFlowEngine {
    private final Disruptor<StepEvent> disruptor;
    private final RingBuffer<StepEvent> ringBuffer;

    public DisruptorFlowEngine(List<Step> steps) {
        // 初始化 Disruptor
        this.disruptor = new Disruptor<>(
                new StepEventFactory(),
                1024,
                Executors.defaultThreadFactory()
        );

        // 构建处理器链
        EventHandler<StepEvent>[] handlers = new EventHandler[steps.size()];
        for (int i = 0; i < steps.size(); i++) {
            final Step step = steps.get(i);
            int finalI = i;
            handlers[i] = (event, sequence, endOfBatch) -> {
                StepContext context = event.context;
                step.execute(context);
                if (finalI == steps.size() - 1) {
                    System.out.println("最终结果: " + context.getData());
                }
            };
        }

        disruptor.handleEventsWith(handlers);
        this.ringBuffer = disruptor.getRingBuffer();
    }

    // 构建处理器链（支持顺序和并行）
    private EventHandlerGroup<StepEvent> buildHandlerChain(Object node, EventHandlerGroup<StepEvent> previousGroup) {
        if (node instanceof Step) {
            // 单个步骤：顺序执行
            EventHandler<StepEvent> handler = createStepHandler((Step) node);
            return (previousGroup == null) ?
                    disruptor.handleEventsWith(handler) :
                    previousGroup.then(handler);
        } else if (node instanceof StepChain.ParallelGroup) {
            // 并行组：创建多个并行处理器
            StepChain.ParallelGroup group = (StepChain.ParallelGroup) node;
            List<EventHandler<StepEvent>> handlers = new ArrayList<>();
            for (Step step : group.getSteps()) {
                handlers.add(createStepHandler(step));
            }
            EventHandler<StepEvent>[] handlerArray = handlers.toArray(new EventHandler[0]);
            EventHandlerGroup<StepEvent> parallelGroup = (previousGroup == null) ?
                    disruptor.handleEventsWith(handlerArray) :
                    previousGroup.then(handlerArray);
            // 添加同步屏障，确保并行组完成后继续
            return parallelGroup.then(createBarrierHandler());
        }
        return previousGroup;
    }

    // 创建步骤处理器
    private EventHandler<StepEvent> createStepHandler(Step step) {
        return (event, sequence, endOfBatch) -> {
            StepContext context = event.context;
            step.execute(context);
            System.out.println("执行步骤: " + step.getClass().getSimpleName() + " → " + context.getData());
        };
    }

    // 空处理器（仅用于同步）
    private EventHandler<StepEvent> createBarrierHandler() {
        return (event, sequence, endOfBatch) -> {
        };
    }

    public void start(StepContext context) {
        disruptor.start();
        long sequence = ringBuffer.next();
        StepEvent event = ringBuffer.get(sequence);
        event.context = context;
        ringBuffer.publish(sequence);
    }

    public void shutdown() {
        disruptor.shutdown();
    }

    // Disruptor 事件载体
    static class StepEvent {
        StepContext context;
    }

    static class StepEventFactory implements EventFactory<StepEvent> {
        @Override
        public StepEvent newInstance() {
            return new StepEvent();
        }
    }
}

// 示例步骤实现（a, b, c, d, f, e）
class StepA implements Step {
    @Override
    public void execute(StepContext context) {
        System.out.println("执行步骤 A → " + context.getData());
        context.setData(context.getData() + " → A");
    }
}

class StepB implements Step {
    @Override
    public void execute(StepContext context) {
        System.out.println("执行步骤 B → " + context.getData());
        context.setData(context.getData() + " → B");
    }
}

class StepC implements Step {
    @Override
    public void execute(StepContext context) {
        System.out.println("执行步骤 C → " + context.getData());
        context.setData(context.getData() + " → C");
    }
}

class StepD implements Step {
    @Override
    public void execute(StepContext context) {
        System.out.println("执行步骤 D → " + context.getData());
        context.setData(context.getData() + " → D");
    }
}

class StepE implements Step {
    @Override
    public void execute(StepContext context) {
        System.out.println("执行步骤 E → " + context.getData());
        context.setData(context.getData() + " → E");
    }
}

class StepF implements Step {
    @Override
    public void execute(StepContext context) {
        System.out.println("执行步骤 F → " + context.getData());
        context.setData(context.getData() + " → F");
    }
}

// 其他步骤（C, D, F, E）类似，省略实现...